import * as CryptoJS from 'crypto-js';
const Helper = {
    /**
     * 判断空值
     * @param value
     * @returns {boolean}
     */
    empty: function (value) {
        if (value === null || value === undefined || value === 'undefined' || value === '' || value === 'null') {
            return true;
        }
        return false;
    },

    /**
     * 判断空json
     * @param value
     * @returns {boolean}
     */
    emptyJson: function (value) {
        if (Helper.empty(value)) {
            return true;
        }

        for (let key in value) {
            return false;
        }

        return true;
    },

    /**
     * 判断空数组
     * @param value
     * @returns {boolean}
     */
    emptyArray(value) {
        return !Array.isArray(value) || value.length === 0;
    },

    /**
     * 去除json中null的值
     * @param value
     * @returns {{}}
     */
    clearEmpty(value) {
        if (Helper.empty(value)) {
            return {};
        }

        let result = {};
        for (let v in value) {
            let data = value[v];
            if (Helper.empty(data)) {
                continue;
            }

            if (typeof v == 'object') {
                result[v] = this.clearEmpty(data);
                continue;
            }

            result[v] = data;
        }

        return result;
    },

    /**
     * 获取json中的值 getValueByJsn({a: {b: 1}}, 'a', 'b')
     * @param obj
     * @param params
     * @returns {string|*|string}
     */
    getValueByJson(obj, ...params) {
        if (!obj || !params) {
            return '';
        }

        let len = params.length;
        let value = obj;
        for (let i = 0; i < len; i++) {
            let param = params[i];
            if (!param) {
                return '';
            }

            value = value[param];
            if (!value) {
                return '';
            }

            if (i < len - 1) {
                if (typeof value !== 'object') {
                    return '';
                }
            }
        }

        return value ? value : '';
    },

    /**
     * 获取区间范围内的随机值
     * @param min
     * @param max
     * @returns {*}
     */
    getRandom(min, max) {
        return Math.floor(Math.random() * (max - min)) + min
    },

    /**
     * 随机生成n位字符串
     * @param len
     * @returns {string}
     */
    genRandomStr(len) {
        var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'; // 默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1
        var maxPos = $chars.length;
        var randomStr = '';

        for (let i = 0; i < len; i++) {
            randomStr += $chars.charAt(Math.floor(Math.random() * maxPos));
        }

        return randomStr;
    },

    /**
     * 数组转map
     * @param items
     * @param key
     * @param value
     * @returns {{}}
     */
    array2Map(items, key, value) {
        let map = {};
        if (Array.isArray(items)) {
            for (let i = 0; i < items.length; i++) {
                let keyField = items[i][key];
                if (!Helper.empty(keyField)) {
                    map[keyField] = items[i][value];
                }
            }
        }

        return map;
    },

    /**
     * 获取数组对象中的key值
     * @param arr
     * @param key
     * @returns {*[]}
     */
    getArrayByKey(arr, key = 'id') {
        let res = [];
        if (Helper.emptyArray(arr) || Helper.empty(key)) {
            return res;
        }

        arr.forEach(item => {
            if (!Helper.empty(item[key])) {
                res.push(item[key])
            }
        })

        return res;
    },

    findArray(arr, condition) {
        if (Helper.emptyArray(arr)) {
            return [];
        }

        arr = window.JSON.parse(window.JSON.stringify(arr));

        if (Helper.empty(condition)) {
            return [];
        }

        return arr.filter(item => {
            for (let key in condition) {
                let value = item[key];
                if (value && value.indexOf(condition[key]) == -1) {
                    let children = item.children;
                    if (Helper.emptyArray(children)) {
                        return false;
                    }

                    children = this.findArray(children, condition);
                    if (!Helper.emptyArray(children)) {
                        item.children = children;
                        return true;
                    }

                    return false;
                }
            }

            return true;
        })
    },

    /**
     * 合并json
     * @param source
     * @param target
     */
    mergeJson(source, target) {
        if (Helper.empty(target)) {
            return;
        }
        if (Helper.empty(source)) {
            source = target;
            return;
        }
        for (let attr in target) {
            let targetValue = target[attr];
            let sourceValue = source[attr];

            if (Helper.empty(sourceValue)) {
                source[attr] = targetValue;
                continue;
            }

            if (Array.isArray(targetValue)) {
                if (this.emptyArray(targetValue)) {
                    targetValue = [];
                }
                source[attr] = targetValue;
                continue;
            }

            if (typeof targetValue === 'object') {
                this.mergeJson(sourceValue, targetValue)
                continue;
            }

            source[attr] = targetValue;
        }
    },

    getFirstMessage(message) {
        if (this.emptyJson(message)) {
            return "";
        }

        for (let key in message) {
            let arr = message[key];
            return arr[0].message;
        }

        return "";
    },

    formatDate(date, fmt = 'yyyy-MM-dd HH:mm:ss') { //author: meizz
        if (Helper.empty(date)) {
            return "";
        }
        var o = {
            'M+': date.getMonth() + 1, //月份
            'd+': date.getDate(), //日
            'H+': date.getHours(), //小时
            'm+': date.getMinutes(), //分
            's+': date.getSeconds(), //秒
            'q+': Math.floor((date.getMonth() + 3) / 3), //季度
            S: date.getMilliseconds() //毫秒
        };
        if (/(y+)/.test(fmt))
            fmt = fmt.replace(
                RegExp.$1,
                (date.getFullYear() + '').substr(4 - RegExp.$1.length)
            );
        for (var k in o)
            if (new RegExp('(' + k + ')').test(fmt))
                fmt = fmt.replace(
                    RegExp.$1,
                    RegExp.$1.length == 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length)
                );
        return fmt;
    },

    formatFileSize(size, pointLength, units) {
        let unit;
        units = units || ['B', 'K', 'M', 'G'];
        while ((unit = units.shift()) && size > 1024) {
            size = size / 1024;
        }
        return (unit === 'B' ? size : size.toFixed(pointLength === undefined ? 2 : pointLength)) + unit;
    },

    setReactive(reactive, data) {
        if (Helper.empty(reactive) || Helper.empty(data)) {
            return;
        }

        for (let key in data) {
            reactive[key] = data[key];
        }
    },

    formatAddress(address) {
        if(Helper.emptyJson(address)) {
            return "";
        }
        return Helper.formatStr("{0}{1}{2}{3}{4}{5}", address.provinceName, address.cityName, address.areaName, address.streetName, address.villageName, address.info);
    },

    formatStr(str, ...arg) {
        if (arguments.length > 1) {
            for (var i = 0; i < arguments.length - 1; i++) {
                var reg = new RegExp("\\{" + i + "\\}", "g");
                str = str.replace(reg, "##_" + i + "_##");
            }

            for (var i = 0; i < arguments.length - 1; i++) {
                var reg = new RegExp("##_" + i + "_##", "g");
                let v = arguments[i + 1];
                if (Helper.empty(v)) {
                    v = "";
                }
                str = str.replace(reg, v);
            }
        }
        return str;
    },

    joinUrl(prefix, url) {
        if(Helper.empty(url)) {
            return "";
        }

        if(url.indexOf("http://") > -1 || url.indexOf("https://") > -1) {
            return url;
        }

        return prefix + url;
    },

    /**
     *加密处理
     */
    encryption(src, keyWord) {
        const key = CryptoJS.enc.Utf8.parse(keyWord);
        // 加密
        var encrypted = CryptoJS.AES.encrypt(src, key, {
            iv: key,
            mode: CryptoJS.mode.CFB,
            padding: CryptoJS.pad.NoPadding,
        });
        return encrypted.toString();
    },

    /**
     *  解密
     * @param {*} params 参数列表
     * @returns 明文
     */
    decryption(src, keyWord) {
        const key = CryptoJS.enc.Utf8.parse(keyWord);
        // 解密逻辑
        var decryptd = CryptoJS.AES.decrypt(src, key, {
            iv: key,
            mode: CryptoJS.mode.CFB,
            padding: CryptoJS.pad.NoPadding,
        });

        return decryptd.toString(CryptoJS.enc.Utf8);
    }
}

export default Helper
